from common_data import User, Party
from twisted.web import xmlrpc
from twisted.python import log

PERMISSION_REQUIREMENT_GLOBAL_ADMIN = 1
PERMISSION_REQUIREMENT_PARTY_ADMIN  = 2
PERMISSION_REQUIREMENT_GLOBAL_USER  = 3
PERMISSION_REQUIREMENT_PARTY_USER   = 4
PERMISSION_REQUIREMENT_ANON_USER    = 5

class PermissionException( Exception ):
    pass

class PermissionExceptionUnauthorized( PermissionException ):
    pass

def validateUser( permission_level, user, *args ):
    """ check if submitted user has access to the submitted permission_level
    """
    
    if not int( permission_level ) or not isinstance( user, User ):
        raise PermissionException( 'invalid validation args' )
        return False
    
    # allow all access to global admins
    if user.admin == 1:
        return True
    
    if int( permission_level ) == PERMISSION_REQUIREMENT_GLOBAL_USER:
        if not user or not isinstance( user, User ):
            raise PermissionExceptionUnauthorized( 'user is not authorized to call this method' )
            return False
        
        return True
    elif int( permission_level ) == PERMISSION_REQUIREMENT_PARTY_USER or int( permission_level ) == PERMISSION_REQUIREMENT_PARTY_ADMIN:
        if not int( args[0] ):
            raise PermissionException( 'no party id submited' )
            return False
        
        party_id = int( args[0] )
        
        try:
            party = Party.get( party_id )
        except IndexError:
            raise PermissionException( 'party not found' )
        except:
            log.err( 'could not retrieve party. party_id: %d' % party_id )
            log.err()
            raise PermissionException( 'could not retrieve party' )
        
        """ check users """
        if int( permission_level ) == PERMISSION_REQUIREMENT_PARTY_USER:
            user_list = party.admins + party.users
        else:
            user_list = party.admins
            
        for puser in user_list:
            if puser.id == user.id:
                return True
        
        raise PermissionExceptionUnauthorized( 'user is not authorized to call this method for this party' )
        return False

    elif int( permission_level ) == PERMISSION_REQUIREMENT_GLOBAL_ADMIN:
        if user.admin != 1:
            raise PermissionExceptionUnauthorized( 'user is not authorized to call this method' )
            return False              
        
        return True
    elif int( permission_level ) == PERMISSION_REQUIREMENT_ANON_USER:
        return True
    else:
        raise PermissionException( 'unrecognized permission schema' )
    